package com.example.demo2.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo2.common.Result;
import com.example.demo2.common.TokenUtil;
import com.example.demo2.config.ExcelHeadDataListener;
import com.example.demo2.entity.Customer;
import com.example.demo2.entity.DTO.*;
import com.example.demo2.entity.SysAdmin;
import com.example.demo2.entity.Validation;
import com.example.demo2.exception.ServiceException;
import com.example.demo2.service.CustomerService;
import com.example.demo2.service.ValidationService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private ValidationService validationService;

    @Resource
    JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String emailAuthor;
    @Value("${spring.mail.expireTime}")
    private Integer expireTime;

    // 新增或修改
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdateCustomer(@RequestBody Customer customer) {
        return customerService.saveOrUpdateCustomer(customer);
    }

    // 删除
    @PostMapping("/delete")
    public Result deleteCustomer(@RequestBody Customer customer) {
        return customerService.removeByIdOfCustomer(customer.getId());
    }

    //批量删除
    @PostMapping("/batch/delete")
    public Result batchDeleteCustomer(@RequestBody List<Integer> ids) {
        return Result.success(customerService.removeBatchByIds(ids));
    }

    //修改
    @PostMapping("/update")
    public Result UpdateCustomer(@RequestBody Customer customer) {
        return Result.success(customerService.updateById(customer));
    }
    //
    @GetMapping("getOneCustomer")
    private Result getOneCustomer(@RequestParam Integer id){
        LambdaQueryWrapper<Customer> customerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        customerLambdaQueryWrapper.eq(Customer::getId,id);
        Customer one = customerService.getOne(customerLambdaQueryWrapper);
        return Result.success(one);
    }

    //分页查询
        @PostMapping("/findPage")
    public Result findPage(@RequestBody CustomerDTO customerDTO) {
        return Result.success(customerService.findPageOfCustomer(customerDTO));
    }

//    private void exportExtracted(HttpServletResponse response, List<Customer> list) throws IOException {
//        ExcelWriter writer = ExcelUtil.getWriter(true);
//        writer.setOnlyAlias(true); // 设置只导出有别名的字段
//        writer.setDefaultRowHeight(18); // 设置只导出有别名的字段
//        writer.setFreezePane(1); // 设置冻结行
//        writer.write(list, true);
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        String fileName = URLEncoder.encode("用户信息", "UTF-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//        ServletOutputStream outputStream = response.getOutputStream();
//        writer.flush(outputStream, true);
//        outputStream.close();
//        writer.close();
//    }

    //导出全部v1.0 采用hutool方法
//    @GetMapping("/exportAllInfo")
//    public void exportAllInfo(HttpServletResponse response) throws Exception {
//        List<Customer> list = customerService.list();
//        exportExtracted(response, list);
//    }
//
//    //批量导出v1.0 采用hutool方法
//    @PostMapping("/batch/exportAllInfo")
//    public void batchexportAllInfo(HttpServletResponse response, @RequestBody Map<String,ArrayList> param) throws Exception {
//        List<Customer> idsList = customerService.listByIds(param.get("ids"));
//        exportExtracted(response, idsList);
//    }
    //导出全部v2.0 采用easyexcel方法
    @GetMapping("/newExportAllInfo")
    public void newExportAllInfo(HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
//        String fileName = URLEncoder.encode("用户信息", "UTF-8");
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<Customer> list = customerService.list();
        EasyExcel.write(response.getOutputStream(), Customer.class).autoCloseStream(Boolean.FALSE).sheet("用户信息").doWrite(list);
    }

    //批量导出v2.0 采用easyexcel方法
    @GetMapping("/batch/newExportAllInfo")
    public void newBatchExportAllInfo(HttpServletResponse response, @RequestParam String ids) throws Exception {
        String[] split = ids.split(",");
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (String each : split) {
            arrayList.add(Integer.parseInt(each));
        }
        List<Customer> idslist = customerService.listByIds(arrayList);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        EasyExcel.write(response.getOutputStream(), Customer.class).autoCloseStream(Boolean.FALSE).sheet("用户信息").doWrite(idslist);
    }

    // 导入
    @PostMapping("/newImportAllInfo")
    public void newImportAllInfo(MultipartFile multipartFile) throws IOException {
        EasyExcel.read(multipartFile.getInputStream(), FieldCustomerDTO.class, new ExcelHeadDataListener(customerService)).sheet().doRead();
    }

    // 导入模板
    @GetMapping("/template/ImportAllInfo")
    public void templateImportAllInfo(HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        ArrayList<TemplateImportDTO> list = new ArrayList<>();
        EasyExcel.write(response.getOutputStream(), TemplateImportDTO.class).autoCloseStream(Boolean.FALSE).sheet("用户信息").doWrite(list);
    }
}